package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void processOverOrder() {
        log.info("未支付订单检测！{}", LocalDateTime.now());
        // 1.查询数据库orders表：条件：未支付，下单时间<当前时间-15分钟
        // select * from orders where status = 1 and order_time < 当前时间-15分钟
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        // 2.如果查询到满足条件的订单，则修改订单状态为已取消，取消原因为超时取消
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单超时，自动取消");
            orders.setCancelTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }

    }

    // **每天凌晨1点检查一次是否存在“派送中(4)”的订单，如果存在则修改订单状态为“已完成”
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行一次
    public void processCompletedOrder() {
        log.info("派送中订单检测！{}", LocalDateTime.now());
        // 1.查询数据库orders表：条件：派送中，订单状态=派送中
        // select * from orders where status = 3
        List<Orders> ordersList = ordersMapper.selectByDeliveryStatus(Orders.DELIVERY_IN_PROGRESS);

        // 2.如果查询到满足条件的订单，则修改订单状态为已完成
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            ordersMapper.update(orders);
        }
    }
}
